<template>
  <div class="login-container">
    <div class="header">
      <img src="@/assets/images/logo.png" alt="" />
    </div>
    <div class="box">
      <div class="box-header"></div>
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="addFormRef"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            placeholder="请输入用户名"
            v-model="ruleForm.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            type="password"
            placeholder="请输入密码"
            v-model="ruleForm.password"
          ></el-input>
        </el-form-item>
        <el-button type="primary" class="btn-login" @click="login"
          >登录</el-button
        >
        <el-link type="info" class="link-reg" @click="$router.push('/reg')"
          >去注册账号</el-link
        >
      </el-form>
    </div>
  </div>
</template>

<script>
import { reqLogin } from '@/api/user.js'


export default {
  name: '',
  data () {
    return {
      ruleForm: {
        username: 'admin',
        password: 'itheima-web'
      },
      rules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9]{1,10}$/, message: '用户名必须是1-10位的字母数字', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码必须是6-15位的非空字符串', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      // 校验通过后,再去发出登录的请求
    // 表单有一个validate预校验的方法, 这个方法中有一个参数,是一个布尔值, 校验通过是true,校验失败是false
      this.$refs.addFormRef.validate(async boo => {
        console.log(boo)
        if (!boo) return console.log('校验未通过')
        // const { data: res } = await this.$http({
        //   method: 'post',
        //   url: 'http://www.liulongbin.top:3008/api/login',
        //   data: this.ruleForm
        // })
        const { data: res } = await reqLogin(this.ruleForm)
        if (res.code !== 0) {
          return this.$message.error('登录失败！')
        }
        // 登录成功，提示用户，保存 token，跳转到后台主页
        this.$message.success('登录成功！')
        localStorage.setItem('token', res.token)
        this.$router.push('/')
      })
    }
  }
}
</script>
<style lang='less'  scoped>
.login-container {
  height: 100%;
  width: 100%;
  background: url('../../assets/images/login_bg.jpg') no-repeat center;
  background-size: cover;
  position: relative;
  .header {
    width: 1200px;
    margin: 0 auto;
    user-select: none;
  }
  .box {
    width: 400px;
    height: 270px;
    background-color: #fff;
    padding: 0 30px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    .box-header {
      height: 60px;
      background: url('../../assets/images/login_title.png') no-repeat center;
    }
    .btn-login {
      width: 100%;
    }
  }
}
</style>
